/**
 * <p/>
 * 版本信息：
 * 日期：2015年7月2日
 * Copyright 马丁洛克 Corporation 2015 版权所有
 */
package utils;

import android.text.TextUtils;

import com.qiniu.android.storage.UploadManager;
import com.shishi.tech.paipai.application.BaseApplication;

import org.json.JSONObject;

import java.io.File;

import http.AysncHttpRequest;
import http.RequestMapBean;
import http.ResultCallback;
import http.StaticUrl;
import utils.common.TimeUtils;
import utils.common.ToastUtil;

/**
 * 类描述:七牛上传 文件
 */
public class QiniuUtil {
    private byte[] data;
    private String filePath;
    private File file;
    private int uploadType = 0;//
    private static final int FILE_BINARY = 1;//二进制上传
    private static final int FILE_PATH = 2;//路径上传
    private static final int FILE_UP = 3;//文件上传
    private UploadManager uploadManager = new UploadManager();
    private QiUpCompletionHandler upCompleteHandler;

    public static QiniuUtil _qiniu;
    public static QiniuUtil getInstance() {
        if (null == _qiniu) {
            _qiniu = new QiniuUtil();
        }
        return _qiniu;
    }


    /**
     * 上传
     * @param module 项目实际模块命名
     * @param type 文件类型定义  资源文件名组成： 模块名/文件类型/UUID.文件后缀
     * @param data 上传的数据
     * @param completionHandler 上传完成后续处理动作
     */
    public void upload(QiniuUploadModule module, QiniuUploadType type, byte[] data,QiUpCompletionHandler completionHandler){
        this.uploadType = FILE_BINARY;
        this.data = data;
        this.upCompleteHandler = completionHandler;
        this.putType(module,type);
    }

    /**
     * 上传
     * @param module 项目实际模块命名
     * @param type 文件类型定义  资源文件名组成： 模块名/文件类型/UUID.文件后缀
     * @param filePath 上传路径
     * @param completionHandler 上传完成后续处理动作
     */
    public void upload(QiniuUploadModule module, QiniuUploadType type, String filePath, QiUpCompletionHandler completionHandler){
        this.uploadType = FILE_PATH;
        this.filePath = filePath;
        this.upCompleteHandler = completionHandler;
        this.putType(module,type);
    }

    /**
     * 上传
     * @param module 项目实际模块命名
     * @param type 文件类型定义  资源文件名组成： 模块名/文件类型/UUID.文件后缀
     * @param file 上传文件
     * @param completionHandler 上传完成后续处理动作
     */
    public void upload(QiniuUploadModule module, QiniuUploadType type, File file, QiUpCompletionHandler completionHandler){
        this.uploadType = FILE_UP;
        this.file = file;
        this.upCompleteHandler = completionHandler;
        this.putType(module,type);
    }


    /**上次文件*/
    private void putType(QiniuUploadModule module, QiniuUploadType type){
        StringBuffer url = new StringBuffer();
        if (!PhoneUtil.isConnectNet()){
            ToastUtil.showMsg("无网络连接，请检查网络");
            return;
        }
        switch (module){
            case _sys:{

            }break;
            case _album:{//相册
                url.append("album");
            }break;
            case _chat:{//聊天
                url.append("chat");
            }break;
            case _mall:{//店铺
                url.append("mall");
            }break;
            case _phiz:{//表情
                url.append("phiz");
            }break;
            case _circle:{//圈
                url.append("circle");
            }break;
        }
        url.append("/");
        switch (type){
            case img:
                url.append("img");
                break;
            case video:
                url.append("video");
                break;
            case audio:
                url.append("audio");
                break;
        }
        url.append("/");
        if (TextUtils.isEmpty(SharedPreUtil.getInstance().getValue(SharedPreUtil.QINIU_URL))
                || TextUtils.isEmpty(SharedPreUtil.getInstance().getValue(SharedPreUtil.QINIU_TOKEN))){
            requestServerToken(QiniuSpaceType._public,url.toString());
        }else {
            updload(url.toString());
        }

    }

    /**上传七牛*/
    private void updload(String url){
        String suffix = FileUtil.getFileExtension(filePath);
        String key = url + TimeUtils.getCurrentTimeLong() + FileUtil.getRandomNumber();//上传文件名称
        if (!TextUtils.isEmpty(suffix)) {
            key += "." + suffix;
        }
         switch (uploadType){
             case FILE_BINARY:
                 uploadManager.put(data,key,SharedPreUtil.getInstance().getValue(SharedPreUtil.QINIU_TOKEN),upCompleteHandler,null);
                 break;
             case FILE_PATH:
                 uploadManager.put(FileUtil.bitmapToString(filePath),key,SharedPreUtil.getInstance().getValue(SharedPreUtil.QINIU_TOKEN),upCompleteHandler,null);
                 break;
             case FILE_UP:
                 uploadManager.put(file,key,SharedPreUtil.getInstance().getValue(SharedPreUtil.QINIU_TOKEN),upCompleteHandler,null);
                 break;
         }
    }


    /**获取起来上次地址*/
    private void requestServerToken(QiniuSpaceType type, final String url) {
        RequestMapBean requestMap = new RequestMapBean();
        requestMap.put("id", type.getValue());//0-公有空间1-私有空间
        AysncHttpRequest.getInstance().post_common(BaseApplication.getInstance().getApplicationContext(), StaticUrl.CLOUDS_UPTOKEN_TYPEID, requestMap, new ResultCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject res, JSONObject obj) {
                try {
                    SharedPreUtil.getInstance().putValue(SharedPreUtil.QINIU_URL,obj.optString("url"));
                    SharedPreUtil.getInstance().putValue(SharedPreUtil.QINIU_TOKEN,obj.optString("uptoken"));
                    //发起上传文件
                    updload(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(JSONObject errorResponse) {
                ToastUtil.showMsg("上传失败");
            }
        });
    }


}
